package com.meme.util;

import org.apache.log4j.Logger;

import java.awt.Color;

public class MiscUtil
{
	static Logger logger = Logger.getLogger (MiscUtil.class);
	
	public static String makeStringWithSomeSpaces (int spacesCount)
	{
		StringBuffer sb = new StringBuffer ();
		while (-- spacesCount >= 0)
			sb.append(' ');
		
		return sb.toString();
	}
	
	public static boolean isSubSuperRelation (Class subClass, Class superClass)
	{
		if (subClass == null )
			return false;
		
		if (superClass == null)
		{
			if (subClass.equals(Object.class))
				return true;
			else
				return false;
		}
		
		Class parent = subClass;
		while (parent != null)
		{
			parent = parent.getSuperclass();
			
			if ( parent.equals(superClass) )
				return true;
		}
		
		return false;
	}
	
	public static int parseInt (String string, int defaultValue)
	{
		try
		{
			if ( string.startsWith("0x") || string.startsWith("0X") )
				return Integer.parseInt(string.substring(2), 16);
			else
				return Integer.parseInt(string, 10);
		}
		catch (Exception e)
		{
			logger.warn ("parseInt error: " + string);
			return defaultValue;
		}
	}
	
	public static Color parseColor (String string, int defaultColorValue)
	{
		try
		{
			if ( string.startsWith("0x") || string.startsWith("0X") )
			{
				String valueString = string.substring(2);
				int len = valueString.length();
				if (len > 8)
					throw new Exception ("color string length >= 8");
				else if (len <= 6)
					return new Color (Integer.parseInt(valueString, 16));
				else
				{
					if (len == 7)
						valueString = "0" + valueString;
					
					int a = Integer.parseInt(valueString.substring(0, 2), 16);
					int r = Integer.parseInt(valueString.substring(2, 4), 16);
					int g = Integer.parseInt(valueString.substring(4, 6), 16);
					int b = Integer.parseInt(valueString.substring(6, 8), 16);
					
					int agrb = (a << 24) | (r << 16) | (g << 8) | b;
					
					if (a != 0)
						return new Color (agrb, true);
					else
						return new Color (agrb);
				}
					
			}
			else
				return new Color (Integer.parseInt(string, 10));
		}
		catch (Exception e)
		{
			logger.warn ("parseColor, parseInt error: " + string);

			if (defaultColorValue >= 0 && defaultColorValue <= 0xFFFFFF )
				return new Color (defaultColorValue);
			else
				return new Color (defaultColorValue, true);
		}
	}
	
	public static boolean parseBoolean (String string, boolean defaultValue)
	{
		try
		{
			if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("yes"))
				return true;
			else
				return false;
		}
		catch (Exception e)
		{
			logger.warn ("parseInt error: " + string);
			return defaultValue;
		}
	}

}
